package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
 @Override

 public R<List<AddressBook>> getAddressBooks(AddressBook addressBook) {
  addressBook.setUserId(BaseContext.getCurrentId());
  log.info("addressBook:{}", addressBook);
  LambdaQueryWrapper<AddressBook> wrapper = Wrappers.<AddressBook>lambdaQuery()
   .eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId())
   .orderByDesc(AddressBook::getUpdateTime);
  List<AddressBook> list = this.list(wrapper);
  return R.success(list);
 }

 @Override
 public R<String> save1(AddressBook addressBook) {
  Long currentId = BaseContext.getCurrentId();
  addressBook.setUserId(currentId);
  this.save(addressBook);
  return R.success("保存成功");
 }

 @Override
 public R<AddressBook> getDefaultAddressBook() {
  LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
  queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
  queryWrapper.eq(AddressBook::getIsDefault, 1);

  //SQL:select * from address_book where user_id = ? and is_default = 1
  AddressBook addressBook = this.getOne(queryWrapper);

  if (null == addressBook) {
   return R.error("没有找到该对象");
  } else {
   return R.success(addressBook);
  }
 }

 @Override
 public R<AddressBook> setDefault(AddressBook addressBook) {
  LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
  wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
  wrapper.set(AddressBook::getIsDefault, 0);
  //SQL:update address_book set is_default = 0 where user_id = ?
  this.update(wrapper);
  addressBook.setIsDefault(1);
  //SQL:update address_book set is_default = 1 where id = ?
  this.updateById(addressBook);
  return R.success(addressBook);

 }

 @Override
 public R<String> upDateAddress(AddressBook addressBook) {
  Long id = addressBook.getId();
  this.removeById(id);
  this.save(addressBook);
  return R.success("修改成功");
 }
}
